//消息发送、获取
import { Request, Response, NextFunction } from "express";
import * as messageService from "../services/message.service";
import * as mqtt from "../services/mqtt.service";
import { SendMessageDTO } from "../dto/message.dto";
import { MessageType } from "../constants/messageType";

export const sendMessage = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const sender_id = Number((req as any).user.id);
    const input = SendMessageDTO.parse(req.body); // ✅ 自动校验
    const message = await messageService.sendMessage({ ...input, sender_id });
    // ✅ MQTT 推送
    if (input.group_id) {
      messageService.sendGroupMessage(input.group_id, JSON.stringify(message));
    } else if (input.receiver_id) {
      messageService.sendPrivateMessage(sender_id, input.receiver_id, JSON.stringify(message));
    }

    res.safeJson(message, "发送成功");
  } catch (err) {
    next(err);
  }
};

export const getMessageList = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const conversation_id = Number(req.query.conversation_id);
    const cursor = req.query.cursor ? Number(req.query.cursor) : undefined;
    const limit = Number(req.query.limit || 20);

    const list = await messageService.getMessages(
      conversation_id,
      limit,
      cursor
    );
    res.safeJson(list, "获取成功");
  } catch (err) {
    next(err);
  }
};

export const recallMessage = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const messageId = Number(req.body.message_id);
    const userId = Number((req as any).user.id);
    const msg = await messageService.recallMessage(messageId, userId);

    // ✅ MQTT 撤回通知
    if (msg.group_id) {
      mqtt.publish(`im/group/${msg.group_id}`, {
        type: "RECALL",
        message_id: msg.id,
      });
    } else if (msg.receiver_id) {
      const topic = `im/simple/${[userId, Number(msg.receiver_id)]
        .sort((a, b) => a - b)
        .join("_")}`;
      mqtt.publish(topic, {
        type: "RECALL",
        message_id: msg.id,
      });
    }

    res.safeJson(null, "已撤回");
  } catch (err) {
    next(err);
  }
};
